'use client';

import { useState, useEffect } from 'react';

export default function NotificationPage() {
  const [notificationPermission, setNotificationPermission] = useState<NotificationPermission>(
    'default'
  );

  // 检查当前通知权限状态
  useEffect(() => {
    if (typeof window !== 'undefined') {
      setNotificationPermission(Notification.permission);
    }
  }, []);

  // 请求通知权限
  const requestNotificationPermission = async () => {
    if (typeof window !== 'undefined' && Notification.permission !== 'granted') {
      const permission = await Notification.requestPermission();
      setNotificationPermission(permission);
      return permission === 'granted';
    }
    return Notification.permission === 'granted';
  };

  // 显示通知
  const showNotification = (title: string, options?: NotificationOptions) => {
    if (Notification.permission === 'granted') {
      // 检查浏览器是否支持Notification
      if ('Notification' in window) {
        new Notification(title, options);
      }
    }
  };

  // 点击按钮触发通知
  const handleNotifyClick = async () => {
    // 先检查权限
    const hasPermission = await requestNotificationPermission();
    
    if (hasPermission) {
      showNotification('这是一条通知', {
        body: '你点击了通知按钮',
        icon: '/favicon.ico', // 可选，通知图标
        vibrate: [200, 100, 200], // 可选，振动模式（仅移动设备）
        data: { url: '/home' } // 可选，附加数据
      }as NotificationOptions & { vibrate?: number[] });
    } else {
      alert('请允许通知权限才能接收通知');
    }
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen p-4">
      <h1 className="text-2xl font-bold mb-6">系统通知示例</h1>
      
      <button
        onClick={handleNotifyClick}
        className="px-6 py-3 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 transition-colors"
      >
        发送系统通知
      </button>
      
      <div className="mt-4 text-gray-600">
        当前通知权限: {notificationPermission}
      </div>
    </div>
  );
}
